#include "loading.h"
#include "ui_loading.h"

Loading *Loading::self = NULL;
Loading *Loading::Instance(QWidget *parent, QColor maskColor, bool touchThrough, QString label)
{
    if (!self) {
        static QMutex mutex;
        QMutexLocker locker(&mutex);
        if (!self) {
            self = new Loading(parent, maskColor, touchThrough, label);
        }
    }
    self->maskColor = maskColor;
    self->setAttribute(Qt::WA_TransparentForMouseEvents, touchThrough);
    self->ui->label->setText(label);

    return self;
}

Loading::Loading(QWidget *parent, QColor maskColor, bool touchThrough, QString label) :
    QWidget(parent),
    ui(new Ui::Loading)
{
    ui->setupUi(this);

    if (windowWidth >= 1280) {
        this->setGeometry(0,0,1280,800);
    }
    setAttribute(Qt::WA_TranslucentBackground, true);
    setAttribute(Qt::WA_TransparentForMouseEvents, touchThrough);
    this->setWindowFlags(this->windowFlags() | Qt::SubWindow);
    timer = new QTimer(this);
    timer->setInterval(20);
    mPix.load(":/resources/loading.png");
    this->maskColor = maskColor;
    ui->label->setText(label);

    connect(timer, &QTimer::timeout, this, &Loading::rotateImage);
}

Loading::~Loading()
{
    delete ui;
}

/**
 * @brief Loading::showLoading 弹出加载框
 * @param maskColor 背景遮罩颜色
 * @param touchThrough 点击是否穿透
 * @param label 文本提示
 */
void Loading::showLoading(QColor maskColor, bool touchThrough, QString label)
{
    Loading *loading = Loading::Instance(Project::Instance(), maskColor, touchThrough, label);
    loading->update();
    if (!loading->timer->isActive()) {
        loading->timer->start();
        loading->show();
    }
}

/**
 * @brief Loading::hideLoading 隐藏加载框
 */
void Loading::hideLoading()
{
    Loading *loading = Loading::Instance();
    if (loading->timer->isActive()) {
        loading->timer->stop();
        loading->hide();
    }
}

void Loading::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(this->rect(), maskColor);
}

void Loading::rotateImage()
{
    static int angle = 0;
    angle += 10;
    angle %= 360;
    QMatrix matrix;
    matrix.rotate(angle);
    QPixmap tmp(80,80);
    tmp.fill(Qt::transparent);
    QPainter painter(&tmp);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.translate(40,40);
    painter.rotate(angle);
    painter.translate(-40,-40);
    painter.drawPixmap(0,0,80,80, mPix);
    ui->icon->setPixmap(tmp);
}

